package demo;


import java.util.Arrays;
import java.util.Objects;
import java.util.Random;

public class demo3 {
    private static final Random RANDOM = new Random();
    public static void main(String[] args) {
        int[] arr = {1, 2, 6, 2, 4, 3, 1, 0, 3, 15, 7, 10, 9, 11};
        quickSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void quickSort(int[] arr) throws NullPointerException{
        quickSortInternal(Objects.requireNonNull(arr), 0, arr.length - 1);
    }

    private static void quickSortInternal(int[] arr, int l, int r) {
        if (l >= r) return;
        swap(arr,l,RANDOM.nextInt(l,r + 1));
        int base = arr[l];
        // 左边界
        int lt = l;
        // 右边界
        int gt = r;
        // 遍历的起始索引
        int i = lt + 1;
        while (i <= gt) {
            if (arr[i] < base) {
                swap(arr, i++, lt++ + 1);
            } else if (arr[i] > base) {
                swap(arr, i, gt--);
            } else {
                i++;
            }
        }
        // 基准值归位
        swap(arr, l, lt);
        quickSortInternal(arr, l, lt - 1);
        quickSortInternal(arr, gt, r);
    }

    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

}
